<template>
  <up-popup :show="show" :round="12" mode="bottom" closeOnClickOverlay :safeAreaInsetBottom="false" @close="close">
    <view class="content">
      <view class="top-btn">
        <text class="top-btn-cancel" @click="close">取消</text>
        <text class="top-btn-confirm" @click="handleConfirm">确定</text>
      </view>
      <view class="main">
        <view class="subsection">
          <up-subsection
            mode="subsection"
            :list="subsection.option"
            :current="subsection.current"
            @change="handleSubsectionChange"
            inactiveColor="#5a5a5a"
            activeColor="#125796" />
        </view>
        <view class="input-box">
          <view
            class="input-box-item"
            :class="emptyChatIndexList.includes(index) ? 'input-box-item-error' : index === currentCharIndex ? 'input-box-item-active' : ''"
            v-for="(_, index) in maxLength"
            :key="index"
            @click="handleInputBoxItemCilck(index)">
            {{ inputList[index] ? inputList[index] : '' }}
          </view>
        </view>
        <view class="keybord">
          <view
            class="keybord-item"
            :class="disabledKeyBoardItemList.includes(item) ? 'keybord-item-disabled' : ''"
            v-for="(item, index) in keyboardShowList"
            :key="index"
            @click="handleKeyboardItemCilck(item, index)"
            :style="`color: ${index === keyboardShowList.length - 1 ? '#dd524d' : '#333333'}`">
            {{ item }}
          </view>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<script setup>
  import { computed, reactive, ref } from 'vue';

  const props = defineProps({
    value: {
      type: String,
      default: ''
    },
    validate: {
      type: Boolean,
      default: true
    }
  });

  const emits = defineEmits(['update:value']);
  const normalLicensePlateLength = 7;
  const newEnergyLicensePlateLength = 8;
	// const normalLicensePlateLength = 8;
	// const newEnergyLicensePlateLength = 7;
  const show = ref(false);
  const maxLength = ref(normalLicensePlateLength);
  const inputList = ref([]);
  const subsection = reactive({
    option: ['普通车牌', '新能源车牌'],
    current: 0
  });
  const currentCharIndex = ref(0);
  const emptyChatIndexList = ref([]);
  const areaMap = '渝皖粤京冀沪津晋蒙辽吉黑苏浙闽赣鲁豫鄂湘桂琼川贵云藏陕甘青宁领';
  const otherMap = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ港澳学警挂';
  const secondCharDisabledList = '0123456789港澳学警挂'.split('');
  const extraCharDisabledList = '港澳学警挂'.split('');
  const keyboardAreaList = areaMap.split('').concat('X');
  const keyboardOtherList = otherMap.split('').concat('X');
  const keyboardShowList = computed(() => (currentCharIndex.value ? keyboardOtherList : keyboardAreaList));
  const disabledKeyBoardItemList = computed(() => {
    if (currentCharIndex.value === 0 || currentCharIndex.value >= maxLength.value - 1) return [];
    else if (currentCharIndex.value === 1) return secondCharDisabledList;
    else return extraCharDisabledList;
  });

  const validateHasEmptyChar = (isFullValidate = false) => {
    if (!props.validate) return;
    let validateList = [];
    if (isFullValidate) {
      if (inputList.value.length === maxLength.value) validateList = inputList.value;
      else validateList = [...inputList.value].concat([...Array(maxLength.value - inputList.value.length)].fill(''));
    } else validateList = inputList.value;
    emptyChatIndexList.value = validateList.map((item, index) => (item === '' ? index : null)).filter(item => item !== null);
    return emptyChatIndexList.value.length;
  };

  // 定义方法
  const open = licensePlateNum => {
    if (licensePlateNum) {
      maxLength.value =
        licensePlateNum.length !== normalLicensePlateLength && licensePlateNum.length !== newEnergyLicensePlateLength
          ? normalLicensePlateLength : licensePlateNum.length;
      inputList.value = licensePlateNum.split('');
      subsection.current = licensePlateNum.length === newEnergyLicensePlateLength ? 1 : 0;
      currentCharIndex.value = licensePlateNum.length === maxLength.value ? licensePlateNum.length - 1 : licensePlateNum.length;
    } else {
      maxLength.value = normalLicensePlateLength;
      inputList.value = [];
      subsection.current = 0;
      currentCharIndex.value = 0;
    }
    emptyChatIndexList.value = [];
    show.value = true;
  };

  const close = () => {
    show.value = false;
  };

  const handleConfirm = () => {
    const hasEmptyChar = validateHasEmptyChar(true);
    if (!hasEmptyChar) {
      emits('update:value', inputList.value.slice(0, maxLength.value).join(''));
      show.value = false;
    } else uni.$u.toast('车牌号格式不正确');
  };

  const handleKeyboardItemCilck = (val, index) => {
    if (disabledKeyBoardItemList.value.includes(val)) return;

    const inputLength = inputList.value.length;
    const keyboardLength = keyboardShowList.value.length;

    // 当键盘点击 非删除 且 输入框为非下一项时
    if (index !== keyboardLength - 1 && currentCharIndex.value !== inputLength) {
      inputList.value[currentCharIndex.value] = val;
      currentCharIndex.value = inputLength >= maxLength.value ? maxLength.value - 1 : inputLength;
      validateHasEmptyChar();
      return;
    }
    // 当键盘点击 删除 且 输入内容不为空时
    if (index === keyboardLength - 1 && inputLength !== 0) {
      if (inputList.value.slice(currentCharIndex.value + 1, maxLength.value).some(item => item !== '')) {
        inputList.value[currentCharIndex.value] = '';
        validateHasEmptyChar();
      } else {
					if (inputLength > maxLength.value) inputList.value.pop();
					inputList.value.pop();
					if (inputLength !== maxLength.value) {
					  currentCharIndex.value = inputList.value.length;
						const errorIndex = emptyChatIndexList.value.indexOf(currentCharIndex.value);
						if (errorIndex !== -1) emptyChatIndexList.value.splice(errorIndex, 1);
					}
      }
    }
    // 当键盘点击 非删除 且 输入内容不等于最大长度时
    if (index !== keyboardLength - 1 && inputLength !== maxLength.value) {
      inputList.value.push(val);
      if (inputLength !== maxLength.value - 1) currentCharIndex.value++;
      validateHasEmptyChar();
    }
  };

  const handleInputBoxItemCilck = index => {
    const errorIndex = emptyChatIndexList.value.indexOf(index);
    if (errorIndex !== -1) emptyChatIndexList.value.splice(errorIndex, 1);
    if (index <= inputList.value.length) currentCharIndex.value = index;
  };

  const handleSubsectionChange = index => {
    subsection.current = index;
    const lastMaxLength = maxLength.value;
    if (index === 0) maxLength.value = normalLicensePlateLength;
    else maxLength.value = newEnergyLicensePlateLength;

    if (lastMaxLength === normalLicensePlateLength) {
      if (extraCharDisabledList.includes(inputList.value[lastMaxLength - 1])) {
        inputList.value[newEnergyLicensePlateLength - 1] = inputList.value[lastMaxLength - 1];
        // inputList.value[lastMaxLength - 1] = '';
        inputList.value[inputList.value.length - 2] = '';
        currentCharIndex.value = maxLength.value - 2;
      } else {
				if (inputList.value.length === lastMaxLength) currentCharIndex.value = lastMaxLength - 1;
				else if (inputList.value.length === maxLength.value) currentCharIndex.value = maxLength.value - 1;
				else currentCharIndex.value = inputList.value.length;
			}
    }
    if (lastMaxLength === newEnergyLicensePlateLength) {
      // if (extraCharDisabledList.includes(inputList.value[lastMaxLength - 1])) currentCharIndex.value = maxLength.value - 1;
			console.log('222', inputList.value.length, lastMaxLength, maxLength.value);
      if (inputList.value.length === lastMaxLength) currentCharIndex.value = maxLength.value - 1;
			else if (inputList.value.length === maxLength.value) currentCharIndex.value = maxLength.value - 1;
      else currentCharIndex.value = inputList.value.length;
    }

    // currentCharIndex.value = inputList.value.length >= maxLength.value ? inputList.value.length - 1 : inputList.value.length;
  };

  defineExpose({ open, close });
</script>

<style lang="scss" scoped>
  .content {
    padding: 12px;
    padding-bottom: 18px;

    .top-btn {
      font-size: 16px;
      @include flex-row(space-between);
      padding-bottom: 12px;
      &-cancel {
        color: $uni-text-color-deep-grey;
      }
      &-confirm {
        color: $uni-color-primary;
      }
    }

    .main {
      .subsection {
        width: 50%;
      }

      .input-box {
        margin: 12px 0;
        @include flex-row(space-between);
        &-item {
          @include size(80rpx);
          @include flex-row(center, center);
          border: 1px solid $uni-border-color;
          border-radius: 20rpx;
          box-sizing: border-box;
          font-weight: bold;
          font-size: 30rpx;

          &-active {
            border: 1px solid $uni-color-primary;
          }

          &-error {
            border: 1px solid $uni-color-error;
          }
        }
      }

      .keybord {
        display: grid;
        grid-template-columns: repeat(8, minmax(40rpx, 1fr));
        gap: 12rpx;
        &-item {
          @include flex-row(center, center);
          aspect-ratio: 1 / 1;
          border-radius: 25%;
          border: 1px solid $uni-border-color;

          &-disabled {
            position: relative;
            background-color: #0000000f;
          }
        }
      }
    }
  }
</style>
